<template>
	<view class="recharge">
		<view class="content">
			<view class="collection">
				<text>收款人账户</text>
				<view class="people">
					<input v-model="data.form.mobile" type="number"  maxlength="11" @input="mobileChange"  placeholder="请输入收款账户"    />
<!--				 	<text v-if="data.side.username">*{{data.side.username[data.side.username.length-1]}}</text>-->
          <text class="text_4_24">{{nickname}}</text>
				</view>
			</view>
			<view class="collection">
				<text>{{['支付密码','支付密码','支付密码'][data.type]}}</text>
				<view class="people">
				 	<input  style="width: 100%;" v-model="data.form.password" :password="showPasswords"  placeholder="请输入密码"    />
					<uni-icons color="#F63B29" :type="!showPasswords?'eye-filled':'eye-slash-filled'" size="20"
						@click="changePasswords"></uni-icons>
					<!-- <text v-if="data.side.username">*{{data.side.username[data.side.username.length-1]}}</text> -->
				</view>
			</view>
			<view class="collMoney">
				<text class="zMOnye">转账金额</text>
				<view class="money">
					<text>￥</text>
					<input    v-model="data.form.money" placeholder="请输入转账金额" />
				</view>
			</view>
			<view class="balance">
				<text class="text">账户{{data.type == 2?'补贴红包':data.type == 0 ? '消费券' : '补贴券' }}：</text>
				<text class="texts">{{$toFiexd(data.type == 2?data.userInfo.subsidy_red:data.money,2)}}</text>
			</view>
		</view>

		<view class="bottomMdd" @click="transfer()">
			<text>转账</text>
		</view>
    <view class="img_cnt_box l_f_c_c_c" v-if="wxQrcode&&data.form.code == 2">
      <image class="img" @longpress="saveImage" :src="wxQrcode" mode="scaleToFill" ></image>
      <view class="l_f_r_c_c">该用户的微信二维码、长按保存。</view>

    </view>
	<!-- 	<view class="record" @click="$goURl('/pages/personal/wallet/balance')">
			<text>转账记录</text>
		</view> -->
		<rudon-payWithPassword :displayByParent="pluginShowing" :pwdLength="6" :amount="data.form.money" titleWindow="请输入支付密码"
			titleAmount="支付购买商品" desc=" " descColor="#FB7B00" :needLog="true" :plaintext="false"
			@whenFullfilled="whenPwdReady">
		</rudon-payWithPassword>
		<uni-popup ref="popup" type="center">
			<view class="popupcontent">
				<uni-icons class="closeempty" type="closeempty" size="22" @click="popup.close()"></uni-icons>
				<view class="title">
					请补全收款人姓名
				</view>
				<view class="input">
					<input v-model="data.name"  maxlength="1" placeholder="姓"  @input="handleProving"  />
					<view class="titles" v-if="data.side.username">
						*{{data.side.username[data.side.username.length-1]}}
					</view>
				</view>
				<view class="bottoms">
					<view class="btn" @click="popup.close()">
						取消
					</view>
					<view class="btns" @click="accounts()">
						确认
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {ref,reactive,getCurrentInstance} from "vue";
	import {onLoad,onShow,onReachBottom} from "@dcloudio/uni-app";
	const { appContext,proxy } = getCurrentInstance();
	const data = reactive({
		userInfo:{},			//用户信息
		name:'',
		money:0,
		form:{
			money:'',
			password:'',
			mobile:'',
			code:0,
		},
		side:'',
		type:","
	})
 async function saveImage() {
    //#ifdef H5
    // 使用fetch API获取图片数据
    const response = await fetch(wxQrcode.value);

    if (!response.ok) {
      throw new Error(`网络请求失败: ${response.status} ${response.statusText}`);
    }

    // 将响应转换为Blob
    const blob = await response.blob();

    // 创建Object URL
    const blobUrl = URL.createObjectURL(blob);

    // 创建下载链接
    const a = document.createElement('a');
    a.href = blobUrl;

    // 生成文件名：当前时间戳
    const timestamp = new Date().valueOf();
    a.download = `image_${timestamp}.png`;

    // 使用现代方式创建和触发事件
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true
    });

    // 添加到DOM并触发点击
    document.body.appendChild(a);
    a.dispatchEvent(event);

    // 清理Object URL
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
    }, 100);

    // 显示成功消息
    statusMessage.textContent = '图片下载成功！';
    statusMessage.className = 'status success';

    // 添加按钮动画效果
    downloadBtn.classList.add('downloaded');
    setTimeout(() => {
      downloadBtn.classList.remove('downloaded');
    }, 2000);
    //#endif
    //#ifndef H5
    saveImageToAlbum(wxQrcode.value)
//#endif
  }
  // 保存图片方法（支持网络/本地路径）
  function saveImageToAlbum(imagePath) {
    // 步骤1：判断是否为网络图片（需要先下载）
    if (imagePath.startsWith('http')) {
      uni.showLoading({ title: '下载中...' })
      uni.downloadFile({
        url: imagePath,
        success: res => {
          if (res.statusCode === 200) {
           _saveLocalImage(res.tempFilePath)
          }
        },
        fail: () => uni.showToast({ title: '下载失败', icon: 'none' }),
        complete: () => uni.hideLoading()
      })
    } else {
      // 本地路径直接保存
     _saveLocalImage(imagePath)
    }
  }

  // 实际保存到相册
  function _saveLocalImage(filePath) {
    // 步骤2：检查相册权限
    uni.authorize({
      scope: 'scope.writePhotosAlbum',
      success: () => {
        // 步骤3：保存图片
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: () => uni.showToast({ title: '保存成功' }),
          fail: (err) => {
            console.error(err)
            uni.showToast({ title: '保存失败', icon: 'none' })
          }
        })
      },
      fail: (err) => {
        if (err.errMsg.includes('deny')) {
          // 引导用户打开设置
          uni.showModal({
            title: '权限申请',
            content: '需要相册权限才能保存图片，是否去设置？',
            success: res => {
              if (res.confirm) uni.openSetting()
            }
          })
        }
      }
    })
  }
  const nickname = ref('')
  const wxQrcode=ref('')
  const mobileChange = (e) => {
    const val = e.detail.value
    console.log(val,'val')
    nickname.value = ''
    if (val.length == 11) {
      proxy.$request({
        url: 'api/transfer/?mobile=' + val,
        method: 'get',
        success(res) {
          console.log(res, 'res')
          if (res.errno == 0) {
            nickname.value = res.data.nickname
            wxQrcode.value=res.data.wx_qrcode
          }
        }
      })
    }
  }

	let showPasswords = ref(true)
	let pluginShowing =ref(false)
	let popup =ref()
	onLoad((option)=>{
		data.type = option.code
					data.form.code = option.code

	})
	onShow(()=>{

		appContext.config.globalProperties.$userInfo({
			success(res){
				data.userInfo=res.data
				if (data.type == 0){
					data.money = data.userInfo.money
				}else{
						data.money = data.userInfo.coupon

				}
			}
		})
		console.log(data.type, "data.type");

		console.log('页面onShow')
	})
	function open(){
		if(data.form.mobile==''){
			uni.showToast({
				icon:'none',
				title:'请输入正确的收款账户'
			})
			return
		}

		popup.value.open()

	}

	function changePasswords() {
		showPasswords.value = !showPasswords.value;
	}
	// 点击提现
	function accounts(){
		popup.value.close()
		// if(data.name+data.side.username.substring(1)!=data.side.username){
		// 	uni.showToast({
		// 		icon:'none',
		// 		title:'验证姓名错误'
		// 	})
		// 	return
		// }
		if(data.userInfo.is_pay_password==0){
			uni.showModal({
				title: '您还没有设置支付密码',
					content: '去设置支付密码?',
					success: function (res) {
						if (res.confirm) {
							console.log('用户点击确定');
							appContext.config.globalProperties.$goURl('/pages/personal/password/password?code=1')
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
			})
			return
		}

		if(data.form.money==''){
			uni.showToast({
				icon:'none',
				title:'请输入正确的转账金额'
			})
			return
		}
		pluginShowing.value = true
		setTimeout(()=>{
			pluginShowing.value = false
		}, 200)
	}
	// 输入的密码
	function whenPwdReady(e){
		data.form.password = e
		transfer()
	}
	// 转账接口
	function transfer(){
		if(data.type == 2){
				appContext.config.globalProperties.$request({
					// url: `api/transferExchange/`,
          url: `api/transfer/`,

					method: 'POST',
					data:{
						mobile:data.form.mobile,
						money:parseFloat(data.form.money),
						password:data.form.password,
						code:Number(data.form.code)
					},
					success(res) {
						uni.showToast({
							icon:'none',
							title:res.errmsg
						})
						if(res.errno==0){
							setTimeout(()=>{
								uni.navigateTo({
									url:"/pages/personal/index"
								})
							},1000)
						}
					}
				})
		}else{
			appContext.config.globalProperties.$request({
				url: `api/transfer/`,
				method: 'POST',
				data:{
					mobile:data.form.mobile,
					money:parseFloat(data.form.money),
					password:data.form.password,
					code:Number(data.form.code)
				},
				success(res) {
					uni.showToast({
						icon:'none',
						title:res.errmsg
					})
					if(res.errno==0){
						setTimeout(()=>{
							uni.navigateTo({
								url:"/pages/personal/index"
							})
						},1000)
					}
				}
			})
		}

	}
	// 输入收款人账户 查询
	function handleProving(e){
		if (!(/^1[3456789]\d{9}$/).test(data.form.mobile)) {
			data.side={}
			return false;
		}
		appContext.config.globalProperties.$request({
			url: `api/transfer/?mobile=${data.form.mobile}`,
			method: 'GET',
			success(res) {
				if(res.errno==0){
					if(!res.data.username){
						uni.showToast({
							icon:'none',
							title:'对方未实名不可转账'
						})
					}
					data.side = res.data
				}else{
					// uni.showToast({
					// 	icon:'none',
					// 	title:res.errmsg
					// })
				}
			}
		})
	}
</script>

<style scoped lang="scss">
	page{
		background-color: #F3F6FD;
	}
	.recharge{
		padding: 30upx;
		.content{
			background-color: #fff;
			border-radius: 16rpx;
			overflow: hidden;

		}
		.collection{
			background-color: #fff;
			// border-top: 1px solid #dbdbdb;
			padding: 15px 0;
			text{
				font-size: 15px;
				font-weight: 700;
				color: #333333;
				margin-left: 15px;
			}
			.people{
				width: 92%;
				margin: 0 auto;
				display: flex;
				justify-content: space-between;
				border-bottom: 1px solid #f5f5f5;
				padding: 15px 0;
			}
		}
		.collMoney{
			padding: 15px;
			background-color: #fff;
			margin-top: 10px;
			.zMOnye{
				font-size: 15px;
				font-weight: 700;
				color: #333333;
			}
			.money{
				display: flex;
				margin-top: 10px;
				border-bottom: 1px solid #f5f5f5;
				padding: 10px 0;
			}

		}
		.balance{
			display: flex;
			padding:0 20px 20px 20px;
			background-color: #fff;
			.text{
				font-size: 28rpx;
				color: #333;
				font-weight: 700;
			}
			.texts{
				font-size: 30rpx;
				color: #333;
				font-weight: 700;
			}
		}
		.bottomMdd{
		margin-top: 30upx;
		border-radius: 16rpx;
			text-align: center;
			background-color: #F63B29;
			padding: 10px 0;
			text{
				color: #fff;
				font-size: 30rpx;
			}
		}
		.record{
			text-align: center;
			margin-top: 30upx;
			text{
				color: #333;
				font-size: 28rpx;
			}
		}
	}
	.popupcontent{
		padding: 30upx;
		background-color: #fff;
		border-radius: 30upx;
		width: 80vw;
		position: relative;
		.closeempty{
			position: absolute;
			right: 30upx;
			top: 30upx;
		}
		.title{
			text-align: center;
		}

		.input{
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 30upx 0;
			input{
				width: 30px;
				border:1upx solid #666;
				text-align: center;
				border-radius: 10upx;
				margin: 0 10upx;
			}
			.titles{
				color: #666;
			}
		}
		.bottoms{
			display: flex;
			justify-content: space-around;
			.btn{
				color: #666;
			}
			.btns{
				color: #000;
			}
		}
	}
  .img_cnt_box{
   background-color: #fff;
    padding: 20upx;
    border-radius: 20rpx;
    margin-top: 30rpx;
    .img{
      height: 400rpx;
      width: 400rpx;
      margin-bottom: 30rpx;
    }
  }
</style>
